<template>
  <div class="article-form-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>{{ isEdit ? '编辑文章' : '新建文章' }}</h2>
        <p>{{ isEdit ? '修改文章内容和设置' : '创建新的博客文章' }}</p>
      </div>
      <div class="header-right">
        <el-button @click="$router.back()">返回</el-button>
        <el-button type="primary" @click="saveArticle" :loading="saving">
          {{ isEdit ? '更新' : '发布' }}
        </el-button>
      </div>
    </div>

    <!-- 文章表单 -->
    <div class="form-container">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="article-form"
      >
        <el-row :gutter="24">
          <!-- 左侧：主要内容 -->
          <el-col :span="16">
            <el-card>
              <template #header>
                <span>文章内容</span>
              </template>

              <!-- 标题 -->
              <el-form-item label="文章标题" prop="title">
                <el-input
                  v-model="form.title"
                  placeholder="请输入文章标题"
                  maxlength="100"
                  show-word-limit
                />
              </el-form-item>

              <!-- 摘要 -->
              <el-form-item label="文章摘要" prop="summary">
                <el-input
                  v-model="form.summary"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入文章摘要"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>

              <!-- 内容 -->
              <el-form-item label="文章内容" prop="content">
                <div class="editor-container">
                  <!-- 这里可以集成富文本编辑器，如 wangEditor、Quill 等 -->
                  <el-input
                    v-model="form.content"
                    type="textarea"
                    :rows="20"
                    placeholder="请输入文章内容（支持 Markdown 格式）"
                  />
                </div>
              </el-form-item>
            </el-card>
          </el-col>

          <!-- 右侧：设置 -->
          <el-col :span="8">
            <el-card>
              <template #header>
                <span>文章设置</span>
              </template>

              <!-- 封面 -->
              <el-form-item label="封面图片">
                <div class="cover-upload">
                  <div class="cover-preview">
                    <img
                      v-if="form.cover"
                      :src="getCoverUrl(form.cover)"
                      class="cover-image"
                      @error="handleCoverError"
                    />
                    <div v-else class="cover-placeholder">
                      <el-icon class="cover-uploader-icon"><Plus /></el-icon>
                      <p>点击上传封面</p>
                    </div>
                  </div>
                  <el-upload
                    class="cover-uploader"
                    :show-file-list="false"
                    :before-upload="beforeCoverUpload"
                    :http-request="uploadCover"
                  >
                    <el-button size="small" type="primary">选择封面</el-button>
                  </el-upload>
                  <div class="upload-tip">建议尺寸：800x400px，支持 JPG、PNG 格式，不超过 2MB</div>
                </div>
              </el-form-item>

              <!-- 分类 -->
              <el-form-item label="文章分类" prop="category_id">
                <el-select
                  v-model="form.category_id"
                  placeholder="选择分类"
                  clearable
                >
                  <el-option
                    v-for="category in categories"
                    :key="category.id"
                    :label="category.name"
                    :value="category.id"
                  />
                </el-select>
              </el-form-item>

              <!-- 标签 -->
              <el-form-item label="文章标签">
                <el-select
                  v-model="form.tags"
                  multiple
                  filterable
                  allow-create
                  placeholder="选择或创建标签"
                >
                  <el-option
                    v-for="tag in tags"
                    :key="tag.id"
                    :label="tag.name"
                    :value="tag.id"
                  />
                </el-select>
              </el-form-item>

              <!-- 状态 -->
              <el-form-item label="发布状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio value="published">立即发布</el-radio>
                  <el-radio value="draft">保存草稿</el-radio>
                </el-radio-group>
              </el-form-item>

              <!-- 置顶 -->
              <el-form-item label="是否置顶">
                <el-switch v-model="form.is_top" />
              </el-form-item>

              <!-- 发布时间 -->
              <el-form-item label="发布时间" v-if="form.status === 'published'">
                <el-date-picker
                  v-model="form.published_at"
                  type="datetime"
                  placeholder="选择发布时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>

              <!-- SEO 设置 -->
              <el-divider content-position="left">SEO 设置</el-divider>

              <el-form-item label="SEO 标题">
                <el-input
                  v-model="form.seo_title"
                  placeholder="SEO 标题（留空使用文章标题）"
                />
              </el-form-item>

              <el-form-item label="SEO 描述">
                <el-input
                  v-model="form.seo_description"
                  type="textarea"
                  :rows="3"
                  placeholder="SEO 描述（留空使用文章摘要）"
                />
              </el-form-item>

              <el-form-item label="SEO 关键词">
                <el-input
                  v-model="form.seo_keywords"
                  placeholder="SEO 关键词，用逗号分隔"
                />
              </el-form-item>
            </el-card>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { articleApi, categoryApi, tagApi, uploadApi } from '@/api/admin'

const route = useRoute()
const router = useRouter()

// 表单引用
const formRef = ref(null)

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 保存状态
const saving = ref(false)

// 分类和标签
const categories = ref([])
const tags = ref([])

// 表单数据
const form = ref({
  title: '',
  summary: '',
  content: '',
  cover: '',
  category_id: '',
  tags: [],
  status: 'draft',
  is_top: false,
  published_at: '',
  seo_title: '',
  seo_description: '',
  seo_keywords: ''
})

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  summary: [
    { max: 200, message: '摘要不能超过 200 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ],
  category_id: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ]
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await categoryApi.getCategories()
    categories.value = response.data || []
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取标签列表
const fetchTags = async () => {
  try {
    // 这里应该调用标签API
    const response = await tagApi.getTags()
    tags.value = response.data || []
    
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

// 获取文章详情
const fetchArticle = async (id) => {
  try {
    const response = await articleApi.getArticle(id)
    const article = response.data
    
    form.value = {
      title: article.title || '',
      summary: article.summary || '',
      content: article.content || '',
      cover: article.cover || '',
      category_id: article.category_id || '',
      tags: article.tags?.map(tag => tag.id) || [],
      status: article.status || 'draft',
      is_top: article.is_top || false,
      published_at: article.published_at || '',
      seo_title: article.seo_title || '',
      seo_description: article.seo_description || '',
      seo_keywords: article.seo_keywords || ''
    }
  } catch (error) {
    console.error('获取文章详情失败:', error)
    ElMessage.error('获取文章详情失败')
  }
}

// 封面上传前检查
const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 调试watch
watch(() => form.value.cover, (val) => {
  console.log('form.cover changed:', val)
})

// 封面加载错误处理
const handleCoverError = () => {
  // form.value.cover = '' // 不要清空cover
  ElMessage.error('封面图片加载失败')
}

// 获取封面完整URL
const getCoverUrl = (path) => {
  if (!path) return ''
  if (/^https?:\/\//.test(path)) return path
  const base = import.meta.env.VITE_API_BASE_URL?.replace(/\/$/, '') || ''
  console.log('VITE_API_BASE_URL:', base)
  let url = ''
  if (path.startsWith('/')) {
    url = `${base}${path}`
  } else if (path.startsWith('covers/')) {
    url = `${base}/storage/${path}`
  } else if (path.startsWith('storage/')) {
    url = `${base}/${path}`
  } else {
    url = `${base}/${path}`
  }
  console.log('getCoverUrl result:', url)
  return url
}

// 上传封面
const uploadCover = async (options) => {
  try {
    const response = await uploadApi.uploadCover(options.file)
    console.log(response)
    // 只存相对路径
    const coverPath = response.data.cover_path
    form.value.cover = coverPath
    ElMessage.success('封面上传成功')
  } catch (error) {
    console.error('封面上传失败:', error)
    ElMessage.error('封面上传失败')
  }
}

// 保存文章
const saveArticle = async () => {
  try {
    await formRef.value.validate()
    saving.value = true
    
    const data = { ...form.value }
    
    if (isEdit.value) {
      await articleApi.updateArticle(route.params.id, data)
      ElMessage.success('文章更新成功')
    } else {
      await articleApi.createArticle(data)
      ElMessage.success('文章创建成功')
    }
    
    router.push('/admin/articles')
  } catch (error) {
    if (error !== false) { // 不是表单验证错误
      console.error('保存文章失败:', error)
      ElMessage.error('保存文章失败')
    }
  } finally {
    saving.value = false
  }
}

// 组件挂载
onMounted(async () => {
  await Promise.all([
    fetchCategories(),
    fetchTags()
  ])
  
  if (isEdit.value) {
    await fetchArticle(route.params.id)
  }
})
</script>

<style scoped lang="scss">
.article-form-page {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;

    .header-left {
      h2 {
        margin: 0 0 8px 0;
        font-size: 24px;
        color: #303133;
      }

      p {
        margin: 0;
        color: #909399;
        font-size: 14px;
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .form-container {
    .article-form {
      .editor-container {
        border: 1px solid #dcdfe6;
        border-radius: 4px;
      }

      .cover-upload {
        .cover-preview {
          border: 1px solid #dcdfe6;
          border-radius: 6px;
          overflow: hidden;
          margin-bottom: 12px;

          .cover-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            display: block;
          }

          .cover-placeholder {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 200px;
            color: #909399;
            background: #fafafa;
            border: 1px dashed #d9d9d9;

            .cover-uploader-icon {
              font-size: 32px;
              margin-bottom: 8px;
            }

            p {
              margin: 0;
              font-size: 14px;
            }
          }
        }

        .cover-uploader {
          text-align: center;
          margin-bottom: 8px;
        }

        .upload-tip {
          font-size: 12px;
          color: #909399;
          text-align: center;
          line-height: 1.4;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .article-form-page {
    .page-header {
      flex-direction: column;
      gap: 16px;

      .header-right {
        align-self: stretch;
        justify-content: flex-end;
      }
    }

    .form-container {
      .el-row {
        .el-col {
          width: 100% !important;
          margin-bottom: 24px;
        }
      }
    }
  }
}
</style> 